{% extends "base.html" %}

{% block title %}添加路由{% endblock %}

{% block head %}
{{ super() }}
{% endblock %}


{% block content %}
<!-- 页面头 -->
<section class="content-header" xmlns="http://www.w3.org/1999/html">
  <!--头部标题-->
  <h1>
    添加路由
    <small>选择命名空间</small>
  </h1>
  <!--面包屑-->
  <!--  <ol class="breadcrumb">-->
  <!--    <li><a href="/"><i class="fa fa-home"></i> 主页</a></li>-->
  <!--    <li class="active">资产管理</li>-->
  <!--  </ol>-->
</section>

<!-- 页面内容 -->
<section class="content">
  <div class="row">
    <div class="col-xs-12">

      <div class="box " id="box">
        <!--        <div class="box-header with-border">-->
        <!--          <h3 class="box-title">选择命名空间</h3>-->
        <!--        </div>-->

        <div class="box-body">
          <div class="col-md-3"></div>
          <div class="col-md-6 col-xs-12">
            <!-- 选择命名口空间 -->
            <div class="form-group">
              <center><label>1 选择命名空间</label></center>
              <select class="form-control" id="selectNamespace">
                <option>--请选择--</option>
              </select>
            </div>

            <!-- 选择/新建Ingress -->
            <div class="form-group">
              <center><label>2 选择/新建Ingress</label></center>
              <div class="radio">
                <label>
                  <input class="radioIngress" type="radio" name="optionsRadios" id="optionExistIngress"
                         value="existIngress" checked
                         disabled>
                  选择已有Ingress
                </label>
              </div>
              <select class="form-control" id="selectIngress" disabled>
                <option>--请选择--</option>
              </select>
              <div class="radio">
                <label>
                  <input class="radioIngress" type="radio" name="optionsRadios" id="optionNewIngress" value="newIngress"
                         disabled>
                  新建Ingress
                </label>
                <!--                <input type="text" id="newIngressName" class="form-control" placeholder="请输入新Ingress名..." disabled>-->
              </div>
              <div class="form-horizontal">
                <div class="form-group">
                  <label for="path" class="col-sm-2 control-label">名称<span style="color: red">*</span></label>
                  <div class="col-sm-10">
                    <input type="text" class="form-control" id="newIngressName" placeholder="" disabled>
                  </div>
                </div>
                <div class="form-group">
                  <label for="path" class="col-sm-2 control-label">改写</label>
                  <div class="col-sm-10">
                    <input type="text" class="form-control" id="newTargetRewrite" placeholder="非必填" disabled value="/$2">
                  </div>
                </div>
              </div>

            </div>

            <!-- 选择/新建规则 -->
            <div class="form-group" id="radioRule">
              <center><label>3 选择/新建规则</label></center>
              <div class="radio">
                <label>
                  <input type="radio" name="optionsRadios_rule" id="optionExistRule" value="existRule" checked
                         disabled>
                  选择已有规则
                </label>
              </div>
              <select class="form-control" id="selectRule" disabled>
                <option>--请选择--</option>
              </select>
              <div class="radio">
                <label>
                  <input type="radio" name="optionsRadios_rule" id="optionNewRule" value="newRule" disabled>
                  新建规则
                </label>
              </div>
              <div class="form-horizontal">
                <div class="form-group">
                  <label for="path" class="col-sm-2 control-label">域名</label>
                  <div class="col-sm-10">
                    <input type="text" class="form-control" id="host" placeholder="非必填" disabled>
                  </div>
                </div>
              </div>

            </div>

            <!-- 新建path -->

            <!-- form start -->
            <form class="form-horizontal">
              <center><label>4 新建路由</label></center>

              <div class="form-group">
                <label for="path" class="col-sm-2 control-label">路径<span style="color: red">*</span></label>
                <div class="col-sm-10">
                  <input type="text" class="form-control" id="path" placeholder="">
                </div>
              </div>
              <div class="form-group">
                <label for="back_svc" class="col-sm-2 control-label">后端服务<span style="color: red">*</span></label>
                <div class="col-sm-10">
                  <input type="text" class="form-control" id="back_svc" placeholder="">
                </div>
              </div>
              <div class="form-group">
                <label for="back_svc" class="col-sm-2 control-label">后端端口<span style="color: red">*</span></label>
                <div class="col-sm-10">
                  <input type="text" class="form-control" id="back_port" placeholder="">
                </div>
              </div>
            </form>

            <center>
              <button type="button" class="btn btn-success" id="addBtn">添加路由</button>
            </center>

          </div>


        </div>
        <div class="col-md-3"></div>

      </div>
      <!-- /.box-body -->
    </div>
    <!-- /.box -->

  </div>
  <!-- /.col -->
  </div>
  <!-- /.row -->
</section>
<!-- /.页面内容 -->
{% endblock %}


{% block script %}

<script>
    var namespace
    var ingressdata
    // 解析URL
    var pathName = window.document.location.pathname;
    console.log(pathName)
    var pathList = pathName.split("/")        // 例如 /cluster/ 被解析为 ['', 'cluster', '']
    console.log(pathList)
    var cluster_id = pathList[3]

    // 一些开启、关闭的快捷方式

    function enableIngress() {
        $('#optionExistIngress').removeAttr('disabled')
        $('#selectIngress').removeAttr('disabled')
        $('#optionNewIngress').removeAttr('disabled')
    }

    function disableIngress() {
        $('#optionExistIngress').attr('disabled', 'disabled')
        $('#selectIngress').attr('disabled', 'disabled')
        $('#optionNewIngress').attr('disabled', 'disabled')
        $('#newIngressName').attr('disabled', 'disabled')
        $('#newTargetRewrite').attr('disabled', 'disabled')
    }

    function enableRule() {
        $('#optionExistRule').removeAttr('disabled')
        $('#selectRule').removeAttr('disabled')
        $('#optionNewRule').removeAttr('disabled')
    }

    function disableRule() {
        $('#optionExistRule').attr('disabled', 'disabled')
        $('#selectRule').attr('disabled', 'disabled')
        $('#optionNewRule').attr('disabled', 'disabled')
        $('#host').attr('disabled', 'disabled')
    }


    // 调用k8sapi获取namespace，添加到下拉菜单中
    function refreshNamespace(cluster_id) {
        console.log("refresh namespace");
        $.get('/api/v1/cluster/' + cluster_id + '/namespaces', function (data) {
            for (var i in data.items) {
                $("#selectNamespace").append('<option value="' + data.items[i].metadata.name + '">' + data.items[i].metadata.name + '</option>');
            }
        });
    }

    // 调用k8sapi获取该namespace下的ingress，并添加到下拉菜单中
    function refreshIngress(cluster_id, namespace) {
        $("#selectIngress").find('option').remove();
        $("#selectIngress").append('<option value="">--请选择--</option>');
        console.log("refresh ingress");
        $.get('/api/v1/cluster/' + cluster_id + '/namespaces/' + namespace + "/ingressname/", function (data) {
            ingressdata = data
            for (var i in data.data) {
                $("#selectIngress").append('<option value="' + data.data[i].name + '">' + data.data[i].name + '</option>');
            }
        });
    }

    // 将某ingress的所有规则添加到下拉菜单中
    function refreshRules(ingress_name) {
        $("#selectRule").find('option').remove();
        $("#selectRule").append('<option value="">--请选择--</option>');
        console.log("refresh rules");
        for (let i in ingressdata.data) {
            if (ingressdata.data[i].name == ingress_name) {
                for (let j in ingressdata.data[i].rules) {
                    $("#selectRule").append('<option value="' + ingressdata.data[i].rules[j].rule_index + '">' + ingressdata.data[i].rules[j].rule_index + ' ' + ingressdata.data[i].rules[j].host + '</option>');
                }

            }

        }
    }

    // 检测选择了namespace，则解锁选择/新建Ingress
    $("#selectNamespace").change(function () {
        namespace = $('#selectNamespace').val()
        console.log(namespace)
        if (namespace != "--请选择--") {
            enableIngress()
            refreshIngress(cluster_id, namespace)
        } else {
            disableIngress()
            disableRule()
        }

    })

    // 检测到Ingress单选框变化
    $(".radioIngress").change(function () {
        console.log("radio Ingress changed")
        let checkedValue = $("input[name='optionsRadios']:checked").val();
        console.log(checkedValue)
        if (checkedValue == 'newIngress') {
            $('#selectIngress').attr('disabled', 'disabled')
            $('#newIngressName').removeAttr('disabled')
            $('#newTargetRewrite').removeAttr('disabled')

            $('#optionExistRule').attr('disabled', 'disabled')

            $('#selectRule').attr('disabled', 'disabled')
            $('#optionNewRule').removeAttr('disabled')

            $('#host').removeAttr('disabled')
            console.log('nnn')


            $('#optionExistRule').attr('checked', false)
            $('#optionNewRule').attr('checked', true)


        } else if (checkedValue == 'existIngress') {
            $('#selectIngress').removeAttr('disabled')
            $('#newIngressName').attr('disabled', 'disabled')
            $('#newTargetRewrite').attr('disabled', 'disabled')
            $('#optionExistRule').removeAttr('disabled')
            let selectIngress = $("#selectIngress").val();
            enableRule()
        }

    })

    // 检测到选择已有Ingress发生变化
    $("#selectIngress").change(function () {
        console.log("select Ingress changed")
        let selectIngress = $("#selectIngress").val();
        console.log(selectIngress)
        if (selectIngress) {
            enableRule()
            refreshRules(selectIngress)
        } else {
            console.log('没有选择任何ingress')
            disableRule()
        }
    })


    // 检测到Rule单选框变化
    $("#radioRule").change(function () {
        console.log("radio rule changed")
        var checkedValue = $("input[name='optionsRadios_rule']:checked").val();
        console.log(checkedValue)
        if (checkedValue == 'newRule') {
            $('#selectRule').attr('disabled', 'disabled')
            $('#host').removeAttr('disabled')
        } else if (checkedValue == 'existRule') {
            $('#optionExistRule').removeAttr('disabled')
            $('#selectRule').removeAttr('disabled')
            $('#host').attr('disabled', 'disabled')
        }
    })

    // 点击了下一步按钮
    $('#addBtn').click(function () {
        // 1 检测namespace
        console.log("namespace: " + namespace)
        if (!namespace || namespace == '--请选择--') {
            alert('无效的命名空间')
            return
        }
        // 2 检测ingress
        let ingress_checked = $('input[name="optionsRadios"]:checked').val()
        console.log("ingress_checked: " + ingress_checked)
        let ingress_name, ingress_rewrite
        if (ingress_checked == 'existIngress') {
            ingress_name = $('#selectIngress').val()
        } else if (ingress_checked == 'newIngress') {
            ingress_name = $('#newIngressName').val()
            ingress_rewrite = $('#newTargetRewrite').val()
        }
        console.log("ingress_name: " + ingress_name)
        console.log("ingress_rewrite: " + ingress_rewrite)
        if (!ingress_name) {
            alert('无效的ingress')
            return
        }
        // 3 检测规则
        let rule_checked = $('input[name="optionsRadios_rule"]:checked').val()
        console.log("rule_checked: " + rule_checked)
        let rule_index, host
        if (rule_checked == 'existRule') {
            rule_index = $('#selectRule').val()
            if (!rule_index) {
                alert('无效的rule')
                return
            }
            for (let i in ingressdata.data) {
                if (ingressdata.data[i].name == ingress_name) {
                    host = ingressdata.data[i].rules[rule_index].host
                    break
                }
            }
        } else if (rule_checked == 'newRule') {
            rule_index = -1
            host = $('#host').val()
        }
        console.log("rule_index: " + rule_index)
        console.log("host: " + host)
        // 4 检测路径 后端服务 后端端口
        let path = $('#path').val()
        let back_svc = $('#back_svc').val()
        let back_port = $('#back_port').val()

        if (!path || !back_svc || !back_port) {
            alert('无效的路径、后端服务、后端端口')
            return
        }
        // 发送
        console.log("调用后端接口，新增ingress")
        $.ajax({
            url: "/api/v1/proxy/add",
            type: "POST",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            data: JSON.stringify({
                cluster_id: cluster_id,
                namespace: namespace,
                ingress_checked: ingress_checked,
                ingress_name: ingress_name,
                ingress_rewrite: ingress_rewrite,
                rule_checked: rule_checked,
                rule_index: Number(rule_index),
                host: host,
                path: path,
                back_svc: back_svc,
                back_port: Number(back_port),
            }),
            success: function (data) {
                console.log(data)
                if (data.code < 399) {
                    bootbox.alert('添加路由成功')
                } else {
                    bootbox.alert('添加路由失败，错误码：' + data.code)
                }

            }
        });

    })

    $(function () {
        // 调整box大小
        // $('#box').css('height', $(window).height() - 150)
        // $(window).resize(function () {
        //     $('#box').css('height', $(window).height() - 150)
        // })

        // 载入页面后，获取namespace列表
        refreshNamespace(cluster_id)
    })
</script>
{% endblock %}